package cn.com.mina;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


public class ClientSocketExample {

    @Test
    public void test() {
        String hostname = "127.0.0.1"; // 服务器的IP地址，这里是本地地址
        int port = 9999; // 服务器监听的端口号

        try {
            // 创建Socket实例，与服务器建立连接
            Socket socket = new Socket(hostname, port);

            // 打开到Socket的输入输出流
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 向服务器发送一条消息
            out.println("Hello, Server!");

            // 从服务器读取响应
            String response = in.readLine();
            System.out.println("Server response: " + response);

            // 关闭流和Socket
            in.close();
            out.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
